package com.woniuxy.run.user.interceptor;

import com.woniuxy.run.user.utils.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器，当用户没登录时访问需要登录的功能时，忽略该请求
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redis;

    //该方法在访问接口之前执行
    //判断用户是否登录
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        //如果用户访问的是登录、注册或者登出 ，直接放行
        if(StringUtils.contains(uri,"user/login") || StringUtils.contains(uri,"user/regist") ||
                StringUtils.contains(uri,"user/logout")){
            return true;
        }
        //判断redis之中有没有该用户
        String token = request.getHeader("token");
        //如果没有表示，用户没有登录
        if(StringUtils.isBlank(token) || !redis.exists(token)){
            //忽略该请求
            return false;
        }else {
            //表示已经登录，放行
            return true;
        }
    }
}
